package com.ls.utils;

import com.ls.constant.SystemConstants;
import com.ls.exception.SysException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description:
 * @author: 朱传捷  80004071
 * @date: 2019-08-12 11:15
 */

@Slf4j
public class UploadUtil {

    /**
     * 上传文件到本地服务器磁盘
     * @param
     * @param file
     * @return
     */
    public static String uploadFile(String fileName, MultipartFile file) {

        //服务器端保存的文件对象
        File serverFile = new File(fileName);
        try {
            //判断文件是否已经存在
            if (serverFile.exists()) {
                throw new SysException("文件已经存在");
            }
            //判断文件父目录是否存在
            if (!serverFile.exists()) {
                serverFile.mkdir();
            }
            //将上传的文件写入到服务器端文件内
            file.transferTo(serverFile);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return fileName;
    }

    public static String writeFile(MultipartFile file, String uploadPath) {
        String filename = file.getOriginalFilename();
        try {
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);
            String name = UploadUtil.genImageName()+ "." + suffix;
            String reg =".+(.png|.jpeg|.jpg)$";
            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher(name);
            if (!matcher.find()){
                return SystemConstants.STRING_0;
            }
            File upload = new File(uploadPath, name);
            if (!upload.getParentFile().exists()) {
                upload.getParentFile().mkdirs();
            }
            file.transferTo(upload);
            return name;
        }catch (IOException e){
            log.error("文件写入失败", e);
        }
        return filename;
    }


    /**
     * 文件下载
     * @param path 服务器上的磁盘文件路径
     * @param response
     * @return
     */
    public static int downloadFile(String path, HttpServletResponse response) {
        int result = 1;
        InputStream is = null;
        OutputStream os = null;
        try {

            File file = new File(path);
            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "utf-8"));
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            is = new FileInputStream(file);
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = 0;
        } finally {
            closeInputStream(is);
            closeOutputStream(os);
        }

        return result;
    }

    private static void closeInputStream(InputStream is) {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void closeOutputStream(OutputStream os) {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 生成随机文件名
     */
    public static String genImageName() {
        //取当前时间的长整形值包含毫秒
        long millis = System.currentTimeMillis();
        //加上三位随机数
        Random random = new Random();
        int end3 = random.nextInt(999);
        //如果不足三位前面补0
        String str = millis + String.format("%03d", end3);

        return str;
    }


}
